/*
 * Copyright ©2021 su binglun(9085309@qq.com). All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *---------------------------------------------------------------------
 *-                                                                   -
 *-           Website : http://phoenix.sunny360.cn/                   -
 *-                                                                   -
 *---------------------------------------------------------------------
 */
package cn.sunny360.client;

import cn.sunny360.messsage.MsgRequest;
import cn.sunny360.messsage.MsgResult;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.ext.web.client.WebClient;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LoginDialog extends JDialog {

	private final JPanel contentPanel = new JPanel();
	private JTextField textField;
	private JTextField textField_1;
	private Vertx vertx;
	private MainWin mainWin;
	

	/**
	 * Create the dialog.
	 */
	public LoginDialog(MainWin mainWin, Vertx vertx, Handler<AsyncResult<MsgResult>> handler) {
		this.vertx = vertx;
		this.mainWin = mainWin;
		
		this.setModal(true);
		setTitle("login");
		setBounds(100, 100, 415, 250);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(null);
		
		JLabel label = new JLabel("User name：");
		label.setBounds(23, 35, 99, 15);
		contentPanel.add(label);
		
		textField = new JTextField();
		textField.setBounds(140, 32, 207, 21);
		contentPanel.add(textField);
		textField.setColumns(10);
		
		JLabel label_1 = new JLabel("Password：");
		label_1.setBounds(23, 77, 99, 15);
		contentPanel.add(label_1);
		
		textField_1 = new JTextField();
		textField_1.setColumns(10);
		textField_1.setBounds(140, 74, 207, 21);
		contentPanel.add(textField_1);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("OK");
				okButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						if (StringUtils.isBlank(textField.getText()) || StringUtils.isBlank(textField_1.getText()) ) {
							Toolkit.getDefaultToolkit().beep();
			                JOptionPane.showMessageDialog(null, "please input user name and password!", "error", JOptionPane.ERROR_MESSAGE);
			                return;
						}
						doLogin(handler);
					}
				});
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						LoginDialog.this.setVisible(false);
						LoginDialog.this.dispose();
					}
				});
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}
	}
	private void doLogin(Handler<AsyncResult<MsgResult>> handler) {
		MsgRequest msgLogin = MsgRequest.newInstance()
				.setType(0)
				.setUserName(textField.getText())
				.setPassword(textField_1.getText());

		WebClient webClient = WebClient.create(vertx);
		String host = mainWin.textField_host.getText();
		Integer port = Integer.parseInt(mainWin.textField_http_port.getText());

		webClient.post(port, host, mainWin.API_USER_LOGIN)
				.putHeader("content-type", "application/octet-stream")
				.sendBuffer(Buffer.buffer(msgLogin.toByteArray()))
				.onSuccess(response->{
					MsgResult msgResult = MsgResult.newInstance();
					msgResult.parseByteArray(response.body().getBytes());
					if (msgResult.getStatus() == 200) {
						handler.handle(Future.succeededFuture(msgResult));
					} else {
						handler.handle(Future.failedFuture(msgResult.getMsg()));
					}
				}).onFailure(event -> {
					handler.handle(Future.failedFuture("登录失败！原因：" + event.getMessage()));
				});
	}
}
